'use strict';

import Base from './base.js';

let onlineUsers = {};
let onlineCount = 0;
let chatUsers = {};
let chatCount = 0;
let user = {};

export default class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    indexAction() {
        //auto render template file index_index.html
        return this.display();
    }

    /**
     * WebSocket 建立连接时处理
     * @return {}      []
     */
    async openAction() {
        let user = await this.session("user");

        //将新加入用户的唯一标识当作socket的名称，后面退出的时候会用到
        let socket = this.http.socket;
        socket.name = user.id;

        // 检查在线列表，如果不在里面就加入
        if (!onlineUsers.hasOwnProperty(user.id)) {
            onlineUsers[user.id] = user.name;
            // 在线人数+1
            onlineCount++;
        }

        let data = {
            onlineUsers: onlineUsers,
            onlineCount: onlineCount,
            user: user
        };
        this.emit("open", data);
    }

    closeAction() {
        let socket = this.http.socket;

        // 将退出的用户从在线列表中删除
        if (onlineUsers.hasOwnProperty(socket.name)) {
            // 退出用户的信息
            var user = {
                id: socket.name,
                name: onlineUsers[socket.name]
            };

            //删除
            delete onlineUsers[socket.name];
            //在线人数-1
            onlineCount--;

            //向所有客户端广播用户退出
            this.emit('close', {onlineUsers: onlineUsers, onlineCount: onlineCount, user: user});
        }
    }

    async joinAction() {
        let user = await this.session("user");

        // 检查聊天列表，如果不在里面就加入
        if (!chatUsers.hasOwnProperty(user.id)) {
            chatUsers[user.id] = user.name;
            // 在线人数+1
            chatCount++;
        }

        let data = {
            chatUsers: chatUsers,
            chatCount: chatCount,
            user: user
        };
        this.broadcast("join", data, true);
    }

    quitAction() {
        let socket = this.http.socket;

        // 若用户存在于在线列表中
        if (chatUsers.hasOwnProperty(socket.name)) {
            // 退出用户的信息
            var user = {
                id: socket.name,
                name: chatUsers[socket.name]
            };

            // 删除
            delete chatUsers[socket.name];
            // 在线人数-1
            chatCount--;

            // 向所有客户端广播用户退出
            let data = {
                chatUsers: chatUsers,
                chatCount: chatCount,
                user: user
            };
            this.broadcast('quit', data, true);
        }
    }

    chatAction() {
        let socket = this.http.socket;
        this.broadcast('chat', {
            message: this.http.data,
            username: chatUsers[socket.name]
        });
    }

}